/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.api.interceptor;

import com.chinamobile.cmss.lakehouse.api.security.Authenticator;
import com.chinamobile.cmss.lakehouse.common.Constants;
import com.chinamobile.cmss.lakehouse.dao.UserDao;
import com.chinamobile.cmss.lakehouse.dao.entity.UserEntity;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.WebUtils;

@Slf4j
public class SessionHandlerInterceptor implements HandlerInterceptor {

    @Resource
    UserDao userDao;

    @Autowired
    private Authenticator authenticator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // get token
        String token = request.getHeader("token");
        UserEntity userEntity;
        if (StringUtils.isEmpty(token)) {
            String sessionId = request.getHeader(Constants.SESSION_ID);
            if (StringUtils.isBlank(sessionId)) {
                Cookie cookie = WebUtils.getCookie(request, Constants.SESSION_ID);

                if (cookie != null) {
                    sessionId = cookie.getValue();
                }

                if (StringUtils.isBlank(sessionId)) {
                    response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                    log.error("the request header must specify sessionId");
                    return false;
                }
            }
            userEntity = authenticator.getAuthUser(sessionId);
            if (userEntity == null) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                log.error("user not exists ,session id {}", sessionId);
                return false;
            }
        } else {
            userEntity = userDao.findByToken(token);
            if (userEntity == null) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                log.error("user token has expired");
                return false;
            }
        }
        request.setAttribute(Constants.SESSION_USER, userEntity);
        return true;
    }
}
